package com.icesoft.base.manager.dao;

import com.icesoft.base.manager.helper.AuthUser;
import com.icesoft.base.manager.helper.SecurityUtils;
import com.icesoft.core.dao.base.BaseModel;
import com.icesoft.core.dao.base.Model;
import com.icesoft.core.dao.criteria.SelectBuilder;
import com.icesoft.core.dao.suppose.IDaoInterceptor;

public abstract class BaseUserInterceptor implements IDaoInterceptor {
    public abstract void onLoad(BaseModel model, AuthUser user);

    public abstract void onCreate(BaseModel model, AuthUser user);

    public abstract void onUpdate(BaseModel model, AuthUser user);

    public abstract void onDelete(BaseModel model, AuthUser user);

    public abstract void onQuery(SelectBuilder selectBuilder, AuthUser user);

    @Override
    public void onLoad(Model model) {
        AuthUser userModel = getCurrentUser();
        if (userModel != null && (model instanceof BaseModel)) {
            onLoad((BaseModel) model, getCurrentUser());
        }
    }

    @Override
    public void onCreate(Model model) {
        AuthUser userModel = getCurrentUser();
        if (userModel != null && (model instanceof BaseModel)) {
            onCreate((BaseModel) model, getCurrentUser());
        }
    }

    @Override
    public void onUpdate(Model model) {
        AuthUser userModel = getCurrentUser();
        if (userModel != null && (model instanceof BaseModel)) {
            onUpdate((BaseModel) model, getCurrentUser());
        }
    }

    @Override
    public void onDelete(Model model) {
        AuthUser userModel = getCurrentUser();
        if (userModel != null && (model instanceof BaseModel)) {
            onDelete((BaseModel) model, getCurrentUser());
        }
    }

    @Override
    public void onQuery(SelectBuilder selectBuilder) {
        AuthUser userModel = getCurrentUser();
        if (userModel != null && (BaseModel.class.isAssignableFrom(selectBuilder.getFromBuilder().getFromTable()))) {
            onQuery(selectBuilder, getCurrentUser());
        }
    }

    private AuthUser getCurrentUser() {
        return SecurityUtils.getUser();
    }
}
